#include "../tcp_server_v3.hpp"

class echo_server {
private:
    TcpServer server;
public:
    echo_server(uint16_t port) : server(port)
    {
        server.EnableInactiveRelease(5);
        server.SetThreadCount(2);
        server.SetConnectedCallback(bind(&echo_server::handle_connected, this, placeholders::_1));
        server.SetMessageCallback(bind(&echo_server::handle_msg, this, placeholders::_1, placeholders::_2));
        server.SetClosedCallback(bind(&echo_server::handle_close, this, placeholders::_1));
    }

    void start() {
        server.Start();
    }
private:
    void handle_connected(const PtrConnection &con) {
        INF_LOG("client connected, fd = %d, id = %ld", con->Fd(), con->Id());
    }

    void handle_msg(const PtrConnection &con, Buffer *buf) {
        string echo = "echo# ";
        echo += string(buf->ReadPosition(), buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        con->Send(echo.c_str(), echo.size());
    }

    void handle_close(const PtrConnection &con) {
        INF_LOG("client disconnected, fd = %d, id = %ld", con->Fd(), con->Id());
    }
};